import { Injectable } from '@nestjs/common';
import { ResultData } from 'src/common/utils/result';
import { CreateNoticeDto, UpdateNoticeDto, ListNoticeDto } from './dto/index';
import { PrismaService } from '@/module/common/prisma/prisma.service';
import { pickEquals, pickLike } from '@/common/utils/prisma';

@Injectable()
export class NoticeService {
    constructor(
        private readonly prisma: PrismaService
    ) { }
    async create(createNoticeDto: CreateNoticeDto) {
        await this.prisma.notice.create({ data: createNoticeDto });
        return ResultData.ok();
    }

    async findAll(query: ListNoticeDto) {
        let where: any = {
            delFlag: '0',
            ...pickLike(query, ['noticeTitle', 'createBy']),
            ...pickEquals(query, ['noticeType']),
        }
        if (query?.beginTime && query?.endTime) {
            where.createTime = {
                gte: new Date(query.beginTime),
                lte: new Date(query.endTime),
            }
        }
        const [list, total] = await Promise.all([
            this.prisma.notice.findMany({
                where,
                skip: query.pageSize * (query.pageNum - 1),
                take: +query.pageSize,
            }),
            this.prisma.notice.count({
                where,
            }),
        ]);

        return ResultData.ok({
            list,
            total,
        });
    }

    async findOne(noticeId: number) {
        const data = await this.prisma.notice.findUnique({
            where: {
                noticeId
            },
        });
        return ResultData.ok(data);
    }

    async update(updateNoticeDto: UpdateNoticeDto) {
        await this.prisma.notice.update({
            where: {
                noticeId: updateNoticeDto.noticeId,
            },
            data: updateNoticeDto,
        });
        return ResultData.ok();
    }

    async remove(noticeIds: number[]) {
        const data = await this.prisma.notice.updateMany({
            where: {
                noticeId: {
                    in: noticeIds
                },
            },
            data: {
                delFlag: '1',
            },
        });
        return ResultData.ok(data);
    }
}
